
package com.csc440.team2.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;


import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;


import com.csc440.team2.SmilConstants;


/**
 * Implements a file browser allowing the user to select files from the file
 * system.
 * 
 * @author Alex Povkov
 */
public class FileBrowser extends ListActivity
{
    // path types, relative or absolute paths to be displayed
    private enum DISPLAYMODE
    {
        ABSOLUTE, RELATIVE;
    }

    private final DISPLAYMODE displayMode = DISPLAYMODE.ABSOLUTE;
    private List<String> directoryEntries = new ArrayList<String>();
    private File currentDirectory = new File("/");


    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle)
    {
        super.onCreate(icicle);
        browseToRoot();
    }


    /**
     * This function browses to the root-directory of the file-system.
     */
    private void browseToRoot()
    {
        browseTo(new File("/sdcard"));
    }


    /**
     * This function browses up one level relative to currentDirectory
     */
    private void upOneLevel()
    {
        if (this.currentDirectory.getParent() != null)
            this.browseTo(this.currentDirectory.getParentFile());
    }


    /**
     * Browses to a provided directory path
     * 
     * @param aDirectory directory to browse to
     */
    private void browseTo(final File aDirectory)
    {
        if (aDirectory.isDirectory())
        {
            this.currentDirectory = aDirectory;
            fill(aDirectory.listFiles());
        }
        else
        {
            OnClickListener okButtonListener = new OnClickListener()
            {
                @Override
                public void onClick(DialogInterface arg0, int arg1)
                {
                    Intent data = new Intent();
                    data.putExtra(SmilConstants.FILE_PATH, Uri.parse(aDirectory.getAbsolutePath()));
                    setResult(3, data);
                    finish();
                }
            };
            OnClickListener cancelButtonListener = new OnClickListener()
            {
                @Override
                public void onClick(DialogInterface arg0, int arg1)
                {
                // Do nothing
                }
            };
            new AlertDialog.Builder(this).setTitle("Question").setMessage(
                    "Do you want to open that file?\n" + aDirectory.getName())
                    .setPositiveButton("OK", okButtonListener).setNegativeButton("Cancel", cancelButtonListener).show();
        }
    }


    /**
     * Fills the list view with the provided array of files
     * 
     * @param files files to display in the list view
     */
    private void fill(File[] files)
    {
        this.directoryEntries.clear();

        try
        {
            Thread.sleep(10);
        }
        catch (InterruptedException e1)
        {
            e1.printStackTrace();
        }

        // current directory
        this.directoryEntries.add(".");

        // "up one level" navigation
        if (this.currentDirectory.getParent() != null)
            this.directoryEntries.add("..");

        switch (this.displayMode)
        {
            case ABSOLUTE:
                for (File file : files)
                {
                    this.directoryEntries.add(file.getPath());
                }
                break;
            case RELATIVE: // On relative Mode, we have to add the current-path
                // to the beginning
                int currentPathStringLenght = this.currentDirectory.getAbsolutePath().length();
                for (File file : files)
                {
                    this.directoryEntries.add(file.getAbsolutePath().substring(currentPathStringLenght));
                }
                break;
        }

        ArrayAdapter<String> directoryList = new ArrayAdapter<String>(this, R.layout.file_row, this.directoryEntries);

        this.setListAdapter(directoryList);
    }


    @Override
    protected void onListItemClick(ListView l, View v, int position, long id)
    {
        String selectedFileString = this.directoryEntries.get(position);
        if (selectedFileString.equals("."))
        {
            // Refresh
            this.browseTo(this.currentDirectory);
        }
        else if (selectedFileString.equals(".."))
        {
            this.upOneLevel();
        }
        else
        {
            File clickedFile = null;
            switch (this.displayMode)
            {
                case RELATIVE:
                    clickedFile = new File(this.currentDirectory.getAbsolutePath()
                            + this.directoryEntries.get(position));
                    break;
                case ABSOLUTE:
                    clickedFile = new File(this.directoryEntries.get(position));
                    break;
            }
            if (clickedFile != null)
                this.browseTo(clickedFile);
        }
    }
}